Fix ScriptHook_t initialization order #320
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When a ScriptClassDesc_t for is initialized (SCRIPTDESC), it recursively invokes its parents initializers in order to obtain their pHelper member.
Initialization is only done once, so repeated initialization is skipped. Initialization includes assignment of a vector of ScriptHook_t's (DEFINE_SCRIPTFUNC/BEGIN_SCRIPTHOOK), which must be initialized beforehand.
Both of these use (static) globals; Within a translation unit, initialization order is defined to be the same as the order of declaration. So within a translation unit we must define all ScriptHook_t's before the ScriptClassDesc_t using them. A problem occurs with the parent initialization though, since there is no defined order between translation units, meaning initialization of a ScriptClassDesc_t can happen before its ScriptHook_t's, despite being the correct order within its translation unit.
On MSVC it seems this issue is benign. On GCC/Linux however the initialization of a ScriptHook_t essentially cleared whatever happened during the initialization of the ScriptClassDesc_t, meaning many hooks simply didn't work.
This situation is remedied by delaying the initialization of the ScriptClassDesc_t's ScriptHook_t vector to only when the constructor of it is invoked from its translation unit. This is accomplished simply by adding a boolean parameter to the function (GetScriptDesc()) that is true in the global constructor invocation, and false by default (including when doing parent ScriptClassDesc_t initialization). When false, a valid ScriptClassDesc_t pointer is still returned, with the proper value for pHelper, which is all that is needed for the initialization of the child ScriptClassDesc_t. The value of the returned pointer is a fixed memory location, and does not change due to the delayed initialization.
Fixes #244.
Does this PR close any issues?
PR Checklist
develop
branch OR targets another branch with a specific goal in mind